<template>
  <el-dialog :model-value="visible" title="分配角色" width="30%" @close="close">
    <el-form :model="form" :label-width="120">
      <el-form-item label="当前用户">
        <el-input disabled v-model="form.username" />
      </el-form-item>
      <el-form-item label="当前角色">
        <el-input disabled v-model="form.role_name" />
      </el-form-item>
      <el-form-item label="选择角色">
        <el-select v-model="form.rid" placeholder="角色">
          <el-option v-for="item in roles" :key="item.id" :label="item.roleName" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, reactive, getCurrentInstance } from 'vue';
import { getRolesApi, setRoleApi } from '@/api/interface'

const { proxy } = getCurrentInstance() as any

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  row: {
    type: Object,
    default: () => {}
  }
})
const emits = defineEmits(['close'])

const roles = ref()
watch(() => props.visible, (newVal, oldVal) => {
  if (newVal) {
    getRolesApi().then((res: any) => {
      roles.value = res.data
    })
    form.id = props.row.id
    form.username = props.row.username
    form.role_name = props.row.role_name
  }
})

const form = reactive({
  id: undefined,
  rid: undefined,
  username: undefined,
  role_name: undefined,
})

const submit = async () => {
  const res = await setRoleApi(form.id, form)
  if (res.meta.status === 200) {
    proxy.$message.success(res.meta.msg)
    close()
  } else {
    proxy.$message.info(res.meta.msg)
  }
}

const close = () => {
  emits('close')
}
</script>

<style scoped></style>